package com.lbjhan.rpc.serializer;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lbjhan.rpc.common.RpcResponse;
import com.lbjhan.rpc.pojo.User;

import java.io.IOException;

public class JacksonSerializer<T> implements ISerializer {

    private static ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public byte[] serialize(Object obj) throws JsonProcessingException {
        byte[] bytes = objectMapper.writeValueAsBytes(obj);
        return bytes;
    }

    @Override
    public T deserialize(byte[] bytes, Class clazz) throws IOException {
        T t = (T)objectMapper.readValue(bytes, clazz);
        return t;
    }

    public static void main(String[] args) throws IOException {
        JacksonSerializer<RpcResponse> userJacksonSerializer = new JacksonSerializer<>();
//        "responseId":"5273366c-91d1-4555-8a0d-7ff8ab37a695","result":{"id":2,"name":"关羽"}
        byte[] bytes = userJacksonSerializer.serialize(new RpcResponse("5273366c-91d1-4555-8a0d-7ff8ab37a695", null, new User(2, "关羽")));
        System.out.println(bytes.length);
        RpcResponse rpcResponse = userJacksonSerializer.deserialize(bytes, RpcResponse.class);
        System.out.println(rpcResponse);
        /**
         * 21
         * User(id=1, name=tom)
         */
    }
}
